import { getLocationByQR } from 'src/services/qrMapLocationService';
import { getPartByQR } from 'src/services/qrMapService';

// {"CAT":"M-Train","SN":"A101"}

export async function parseLocationQR(string: string) {
  if (string.includes('{') && string.includes('}')) {
    const formatLocation = JSON.parse(
      string.replace(/\n/g, '').replace(/^ +| +$/g, '')
    );
    if (formatLocation.CAT && formatLocation.SN) {
      return formatLocation.CAT + '-' + formatLocation.SN;
    } else {
      try {
        const res = await getLocationByQR(string);
        if (res.data.code == 1) {
          console.log(res.data);

          return res.data.data.category + '-' + res.data.data.train;
        }
      } catch (error) {
        console.log(error);
        return false;
      }
    }
  } else {
    return string;
    // try {
    //   const res = await getLocationByQR(string);
    //   if (res.data.code == 1) {
    //     console.log(res.data);

    //     return res.data.data.category + '-' + res.data.data.train;
    //   }
    // } catch (error) {
    //   console.log(error);
    //   return false;
    // }
  }
}

export async function parsePartQR(string: string) {

  if (string.includes('{') && string.includes('}')) {
    const obj = JSON.parse(string.replace(/\n/g, '').replace(/^ +| +$/g, ''));

    console.log('obj', obj);

    if (obj.CAT && obj.SN) {
      return {
        CAT: obj.CAT,
        SN: obj.SN,
      };
    } else {
      //get map
      try {
        const res = await getPartByQR(string);

        if (res.data.code == 1) {
          return {
            CAT: res.data.data.stock_code,
            SN: res.data.data.serial_no,
          };
        }
        //   else if (res.data.code==0) {
        //     return false
        //   }
      } catch (error) {
        console.log(error);
        return false;
      }
    }
  } else {
    //get map
    try {
      const res = await getPartByQR(string);
      console.log(res.data.data);
      
      if (res.data.code == 1) {
        return {
          CAT: res.data.data.stock_code,
          SN: res.data.data.serial_no,
        };
      }
      //   else if (res.data.code==0) {
      //     return false
      //   }
    } catch (error) {
      console.log(error);
      return false;
    }
  }
}
